<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm" style="margin-bottom: 0">
            <el-form-item label="类型" prop="status">
              <el-select v-model="queryParams.specialtype" class="m-2" placeholder="请选择" clearable @change="handleSearch">
                <el-option
                    v-for="item in specialTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="发布" prop="status">
              <el-select v-model="queryParams.status" class="m-2" placeholder="请选择" clearable @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '上架中' },
                    { value: 0, label: '下架中' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="评论" prop="commentFlag">
              <el-select v-model="queryParams.commentFlag" class="m-2" placeholder="请选择" clearable
                         @change="handleSearch">
                <el-option v-for="item in [{id:1,value:'允许'},{id:2,value:'不允许'}]" :key="item.id"
                           :label="item.value" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="热门" prop="hotFlag">
              <el-select v-model="queryParams.hotFlag" class="m-2" placeholder="请选择" clearable
                         @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '是' },
                    { value: 0, label: '否' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="推荐" prop="pushFlag">
              <el-select v-model="queryParams.pushFlag" class="m-2" placeholder="请选择" clearable
                         @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '是' },
                    { value: 0, label: '否' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="最新" prop="newFlag">
              <el-select v-model="queryParams.newFlag" class="m-2" placeholder="请选择" clearable
                         @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '是' },
                    { value: 0, label: '否' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="打开方式" prop="mode">
              <el-select v-model="queryParams.mode" class="m-2" placeholder="请选择" clearable @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '内站打开' },
                    { value: 2, label: '外站打开' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="支付类型" prop="payFlag">
              <el-select v-model="queryParams.payFlag" class="m-2" placeholder="请选择" clearable
                         @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '免费' },
                    { value: 2, label: '收费' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="可见性" prop="vipFlag">
              <el-select v-model="queryParams.vipFlag" class="m-2" placeholder="请选择" clearable
                         @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '1所有人可见' },
                    { value: 2, label: 'VIP可见' },
                    { value: 3, label: 'SVIP可见' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click.prevent="handleSearch">搜索</el-button>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-container style="border-radius: 8px; margin-top: 10px; background: #fff">
          <el-aside width="200px" style="padding: 10px" v-loading="cateLoading">
            <el-input v-model="filterText" placeholder="请输入板块名称"/>
            <div class="mt10">
              <el-tree
                  ref="treeRef"
                  class="filter-tree"
                  @node-click="handleChangeNode"
                  :data="categoryList"
                  default-expand-all
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span>{{ data.title }}（{{ data.postCount }}）</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-aside>
          <el-main style="--el-main-padding: 10px">
            <div style="margin: 0 0 10px; display: flex; justify-content: space-between">
              <div v-loading="cateLoading" class="flex">
                <el-button type="primary" icon="Plus" @click="handleAdd">添加专题</el-button>
                <el-button type="success" icon="Open" :loading="upLoading" @click="handleBatchStatus('up')"
                >批量上架
                </el-button
                >
                <el-button type="warning" icon="Open" :loading="specialing" @click="handleBatchStatus('down')"
                >批量下架
                </el-button
                >
                <el-button type="danger" icon="close" :loading="delLoading" @click="handleBatchDels()"
                >批量删除
                </el-button
                >
                <el-input v-model="queryParams.keyword" class="ml10" placeholder="名称、用户名、分类名称..."
                          maxlength="100" style="width:200px;" clearable/>
                <el-button type="primary" icon="Search" class="ml10" @click.prevent="handleSearch">搜索</el-button>
              </div>
              <div style="width: 100%" v-if="showAlert" class="ml10">
                <el-alert
                    @close="handleAlertClose"
                    :title="'选中了（' + selectIds.length + '）项数据'"
                    type="success"
                    show-icon
                />
              </div>
              <div class="ml10">
                <el-button type="danger" icon="delete" @click="handleOpenRecycle">回收站</el-button>
              </div>
            </div>
            <el-table
                v-loading="tableLoading"
                ref="tableRef"
                :data="tableData"
                stripe
                border
                @selection-change="handleSelectionChange"
                height="calc(100vh - 305px)"
            >
              <el-table-column fixed type="selection" align="center" width="55"/>
              <el-table-column fixed :label="'总数：' + total" width="100" align="center">
                <template v-slot="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="封面" width="240" align="center">
                <template #default="scope">
                  <el-image :src="scope.row.img" title="点击预览" width="240" :z-index="1000000" preview-teleported
                            :preview-src-list="[scope.row.img]"></el-image>
                </template>
              </el-table-column>
              <el-table-column label="标题" width="260">
                <template #default="scope">
                  <a href="javascript:void(0);" class="fb fw"
                     :title="scope.row.title">标题：{{ scope.row.title }}</a>
                  <p>子标题：{{scope.row.subTitle}}</p>
                  <p>编号：{{scope.row.id}}</p>
                  <p v-if="scope.row.specialtype>0">类型：{{specialTypes.find(c=>c.value==scope.row.specialtype).label}}</p>
                </template>
              </el-table-column>
              <el-table-column label="分类" width="150" align="center">
                <template #default="scope">
                  {{ scope.row.categoryPname }}<span v-if="scope.row.categoryName"> / {{
                    scope.row.categoryName
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="路由标识" width="150" align="center">
                <template #default="scope">
                  {{ scope.row.path }}
                </template>
              </el-table-column>
              <el-table-column label="打开方式" width="140" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.mode" @change="handleStatus(scope.row, 'mode')" style="width: 120px"
                             placeholder="请选择打开方式" clearable>
                    <el-option v-for="item in [{value:1,label:'内站打开'},{value:2,label:'外站打开'}]"
                               :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="价格" width="200">
                <template #default="scope">
                  <div class="flex align-center">
                    <el-tooltip content="售价：" placement="top">
                      <span><el-input v-model="scope.row.realprice"
                                      @blur="handleStatus(scope.row, 'realprice')"></el-input></span>
                    </el-tooltip>
                    <el-tooltip content="原价：" placement="top">
                      <span class="ml5"><el-input v-model="scope.row.price"
                                                  @blur="handleStatus(scope.row, 'realprice')"></el-input></span>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="金币" width="80">
                <template #default="scope">
                  <div class="flex align-center">
                    <el-tooltip content="金币：" placement="top">
                      <span><el-input v-model="scope.row.coin"
                                      @blur="handleStatus(scope.row, 'coin')"></el-input></span>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="支付类型" width="140">
                <template #default="scope">
                  <el-select v-model="scope.row.payFlag" @change="handleStatus(scope.row, 'payFlag')"
                             style="width: 120px" placeholder="请选择支付类型" clearable>
                    <el-option
                        v-for="item in [{value:1,label:'免费'},{value:2,label:'收费'}]"
                        :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="可见性" width="140">
                <template #default="scope">
                  <el-select v-model="scope.row.vipFlag" @change="handleStatus(scope.row, 'vipFlag')"
                             style="width: 120px" placeholder="请选择可见性" clearable>
                    <el-option
                        v-for="item in [{value:1,label:'所有人可见'},{value:2,label:'VIP可见'},{value:3,label:'SVIP可见'}]"
                        :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="网盘地址" width="240">
                <template #default="scope">
                  <div class="flex align-center">
                    <span><el-input v-model="scope.row.panLink"
                                    @blur="handleStatus(scope.row, 'panLink')"></el-input></span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="网盘密码" width="120">
                <template #default="scope">
                  <div class="flex align-center">
                    <span><el-input v-model="scope.row.panPwd"
                                    @blur="handleStatus(scope.row, 'panPwd')"></el-input></span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="体验地址" width="240">
                <template #default="scope">
                  <div class="flex align-center">
                    <span><el-input v-model="scope.row.tryLink"
                                    @blur="handleStatus(scope.row, 'tryLink')"></el-input></span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="作者" prop="nickname" width="100" align="center"/>
              <el-table-column label="阅读数" prop="viewcount" width="100" align="center"/>
              <el-table-column label="喜欢数" prop="likeNum" width="100" align="center"/>
              <el-table-column label="收藏数" prop="favNum" width="100" align="center"/>
              <el-table-column label="评论数" prop="commentNum" width="100" align="center"/>
              <el-table-column label="购买数" prop="buyNum" width="100" align="center"/>
              <el-table-column label="下载数" prop="specialNums" width="100" align="center"/>
              <el-table-column label="是否启用" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.status"
                      @change="handleStatus(scope.row, 'status')"
                      :active-value="1"
                      active-text="上架中"
                      inactive-text="下架中"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="是否热门" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.hotFlag"
                      @change="handleStatus(scope.row, 'hotFlag')"
                      :active-value="1"
                      active-text="是"
                      inactive-text="否"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="是否最新" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.newFlag"
                      @change="handleStatus(scope.row, 'newFlag')"
                      :active-value="1"
                      active-text="置顶"
                      inactive-text="不置顶"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="是否推荐" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.pushFlag"
                      @change="handleStatus(scope.row, 'pushFlag')"
                      :active-value="1"
                      active-text="是"
                      inactive-text="否"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="是否允许评论" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.commentFlag"
                      @change="handleStatus(scope.row, 'commentFlag')"
                      :active-value="1"
                      active-text="是"
                      inactive-text="否"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" width="200" align="center">
                <template #default="scope">
                  <span>{{ formatTimeToStr(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="更新时间" width="200" align="center">
                <template #default="scope">
                  <span>{{ formatTimeToStr(scope.row.updateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="开启群微信" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.clientFlag"
                      @change="handleStatus(scope.row, 'clientFlag')"
                      :active-value="1"
                      active-text="开启"
                      inactive-text="关闭"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="开启公众号" width="200" align="center">
                <template #default="scope">
                  <el-switch
                      v-model="scope.row.opengz"
                      @change="handleStatus(scope.row, 'opengz')"
                      :active-value="1"
                      active-text="开启"
                      inactive-text="关闭"
                      :inactive-value="0"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" width="420">
                <template #default="scope">
                  <el-button icon="Document" type="success" size="small" @click.stop="handleBind(scope.row)">绑定内容
                  </el-button>
                  <el-button icon="edit" type="info" size="small" @click.stop="handleCopy(scope.row)">复制</el-button>
                  <el-button icon="edit" type="primary" size="small" @click.stop="handleEdit(scope.row)"
                  >编辑
                  </el-button
                  >
                  <el-button icon="refresh" type="danger" size="small" @click.stop="handleCache(scope.row)"
                  >刷新缓存</el-button>
                  <el-button icon="remove" type="danger" size="small" @click.stop="handleDel(scope.row)"
                  >删除
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="kva-pagination-box center">
              <el-pagination
                  :current-page="queryParams.pageNo"
                  :page-size="queryParams.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-main>
        </el-container>
      </home-page-header>
    </div>
    <bind-relation ref="bindRelationRef"></bind-relation>
    <add-content ref="addRef" @load="handleLoadSuccess"></add-content>
    <recycle-bin ref="recycleRef" @load="handleLodeData"></recycle-bin>
  </div>
</template>
<script setup>
import KVA from '@/utils/kva.js'
import {formatTimeToStr} from '@/utils/date.js'
import AddContent from './components/AddContent.vue'
import {copyData, batchDels,specialRefresh, findPages, updateStatus, batchDowns, batchUps, delById} from '@/api/special/index.js'
import {findPages as findCategoryTree} from '@/api/special/category.js'
import RecycleBin from './components/RecycleBin.vue'
// 获取状态管理的菜单信息
import {useUserStore} from '@/stores/users.js'
import BindRelation from './components/BindRelation.vue'

const userStore = useUserStore();
const currentSystem = computed(() => userStore.systemList?.filter(c => c.defaultFlag == 1)[0])
const specialTypes = ref([{label:"基础课",value:1},{label:"进阶课",value:2},{label:"实战课",value:3},{label:"面试课",value:4}])
// 搜索属性定义
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  status: '',
  topFlag: '',
  essenceFlag: '',
  categoryPid: '',
  categoryId: '',
  // 类型 1: 文本 2图文 3：视频
  datasource: '',
  specialtype:'',
  keyword: ''
})

// 定义响应式得列表数据容器
const recycleRef = ref({})
const bindRelationRef = ref({})
const tableRef = ref({})
const treeRef = ref({})
const tableHeight = ref('calc(100vh - 315px)')
const categoryList = ref([])
const filterText = ref('')
const tableData = ref([])
const tableLoading = ref(false)
const cateLoading = ref(false)
const delLoading = ref(false)
const specialing = ref(false)
const upLoading = ref(false)
const pages = ref(0)
const total = ref(0)
const searchForm = ref({})
const showAlert = ref(false)
const selectIds = ref([])
// 编辑添加相关
const addRef = ref({})

watch(filterText, (val) => {
  treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.title.includes(value)
}

const handleCache = async (row)=>{
  const resp = await specialRefresh(row.id)
  KVA.notifySuccess('操作成功!')
}

// 加载数据
const handleLodeData = async () => {
  tableLoading.value = true
  const resp = await findPages(queryParams)
  tableLoading.value = false
  tableData.value = resp.data.records
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData()
}

// 重置
const handleReset = () => {
  searchForm.value.resetFields()
  handleSearch()
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData()
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData()
}

// 添加事件
const handleAdd = () => {
  addRef.value.handleOpen(null, categoryList.value)
}

// 编辑
const handleEdit = (row) => {
  addRef.value.handleOpen(row.id, categoryList.value)
}

// 更新状态
const handleStatus = async (row, field) => {
  await updateStatus(row.id, field, row[field])
  KVA.notifySuccess('操作成功!')
  handleLodeData()
}

// 加载板块
const handleLoadCategoryTree = async () => {
  cateLoading.value = true
  const res = await findCategoryTree({})
  categoryList.value = res.data
  cateLoading.value = false
}

// 点击板块搜索
const handleChangeNode = async (node) => {
  if (node.parentId == 0) {
    queryParams.categoryPid = node.id
    queryParams.categoryId = ''
  } else {
    queryParams.categoryPid = node.parentId
    queryParams.categoryId = node.id
  }
  handleSearch()
}

// 清空选择
const handleAlertClose = () => {
  showAlert.value = false
  tableRef.value.clearSelection()
}

/**
 * 选择删除的元素
 * @param rows
 */
const handleSelectionChange = (rows) => {
  selectIds.value = rows.map((c) => c.id)
  showAlert.value = rows.length > 0
  tableHeight.value = rows.length > 0 ? 'calc(100vh - 350px)' : 'calc(100vh - 315px)'
}

/**
 * 批量删除
 */
const handleBatchDels = async () => {
  if (selectIds.value.length == 0) {
    KVA.warning('请选择一项进行操作!')
    return
  }
  KVA.confirm('警告', '<strong>您确定要执行【批量删除】吗？，一旦执行无法恢复！</strong>', {icon: 'success'}).then(
      async () => {
        delLoading.value = true
        await batchDels(selectIds.value.join(','))
        delLoading.value = false
        KVA.notifySuccess('批量删除成功!')
        handleLodeData()
      }
  )
}

// 删除
const handleDel = (row) => {
  KVA.confirm('警告', '<strong>您确定要执行此次操作吗？</strong>', {icon: 'success'}).then(async () => {
    if (row.roleIds && row.roleIds.length > 0) {
      KVA.error('存在绑定关系,无法删除?')
      return
    }
    await delById(row.id, 'isDeleted', 1)
    KVA.notifySuccess('删除成功!')
    handleLodeData()
  })
}

/**
 * 批量上下架
 */
const handleBatchStatus = async (field) => {
  if (selectIds.value.length == 0) {
    KVA.warning('请选择一项进行操作!')
    return
  }
  if (field == 'up') {
    upLoading.value = true
    await batchUps(selectIds.value.join(','))
    upLoading.value = false
  } else {
    specialing.value = true
    await batchDowns(selectIds.value.join(','))
    specialing.value = false
  }
  KVA.notifySuccess('执行成功!')
  handleLodeData()
}

// 复制一条
const handleCopy = async (row) => {
  await copyData(row.id);
  KVA.success("复制成功!!")
  handleLodeData()
}

// 打开回收站
const handleOpenRecycle = () => {
  recycleRef.value.handleOpen()
}

// 刷新加载
const handleLoadSuccess = () => {
  handleLodeData()
  handleLoadCategoryTree()
}

// 打开绑定关系页面
const handleBind = (row) => {
  bindRelationRef.value.handleOpen(row.id, row.title)
}

onMounted(() => {
  handleLodeData()
  handleLoadCategoryTree()
})
</script>
